package com.zc.ai.service.impl;

import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import com.zc.ai.pojo.ChatMessageSingleton;
import com.zc.ai.service.ChatService;
import com.zc.ai.service.openai.OpenAiService;
import com.zc.ai.vo.request.CreateSessionRequest;
import io.reactivex.functions.Action;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import java.util.List;

@Service
public class ChatServiceImpl implements ChatService {
    @Value("${openai.key}")
    private String token;

    public ResponseEntity<StreamingResponseBody> createSession(CreateSessionRequest parameter) {
        List<ChatMessage> messages = ChatMessageSingleton.getInstance();
        final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), parameter.getPrompt());
        messages.add(systemMessage);

        OpenAiService service = new OpenAiService(token);

        StreamingResponseBody responseBody = response -> {
            ChatCompletionRequest request = ChatCompletionRequest.builder()
                    .messages(messages)
                    .stream(true)
                    .model(parameter.getModel())
//                    .maxTokens(4096)
                    .temperature(1.0)
                    .frequencyPenalty(0.3)
                    .presencePenalty(0.3)
                    .build();

            service
                    .streamChatCompletionBytes(request)
                    .doOnError(e -> {
                        e.printStackTrace();
                    })
                    .doOnComplete((Action) () -> {
                        //do something on completion
                    })
                    .blockingForEach(bytes -> {
                        response.write(bytes);
                        response.flush(); //immediately write out buffered bytes
                    });
        };

        return ResponseEntity.ok()
                .contentType(MediaType.TEXT_EVENT_STREAM)
                .body(responseBody);
    }

    @Override
    public void uploadFile(MultipartFile file) {
        OpenAiService service = new OpenAiService(token);
//        service.uploadFile()
    }


}
